package com.sduept.nwld.dataserver.controller.statistics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.nwld.dataserver.manager.statistics.ResponseFeaBreakerManager;
import com.sduept.nwld.dataserver.model.countanalyse.BreakerResponseTimeStatistics;

@Named
@ViewScoped
public class ResponseFeaBreakerController extends AbstractController {

	private static final long serialVersionUID = 8799062522221861107L;
	@Autowired
	private CommonDocumentProperties pros;
	@Autowired
	private ResponseFeaBreakerManager manager;
	
	private List<String> years = new ArrayList<String>();
	private List<Integer> months = new ArrayList<Integer>();
	private List<String> areas = new ArrayList<String>();
	private List<String> voltages = new ArrayList<String>();
	private String area = "all";
	private String year = new String();
	private String month = new String();
	private String voltage = "all";
	private List<BreakerResponseTimeStatistics> breakerResponseTimeStatisticsList = new ArrayList<BreakerResponseTimeStatistics>();
	private BreakerResponseTimeStatistics breakerResponseTimeStatistics = new BreakerResponseTimeStatistics();
	private BreakerResponseTimeStatistics selectBreakerResponseTimeStatistics = new BreakerResponseTimeStatistics();
	
	private StreamedContent templateFile;
	
	@PostConstruct
	public void init() {
		voltages = manager.getAllVoltages();
		areas = manager.getAllAreas();
		voltage = voltages.get(0);
		initYears();
		for (int i = 1; i < 13; i++) {
			months.add(i);
		}
	}
	
	public void initYears() {
		years.clear();
		List<Integer> iyears = manager.getAllYearsByVoltage(voltage);
		if(iyears.size()>1) {
			int min = iyears.get(iyears.size()-1);
			int max = iyears.get(0);
			years.add(min+"~"+max);
		}
		for (Integer s : iyears) {
			years.add(s.toString());
		}
	}
	
	public void resetYearAndVoltage() {
		voltage = voltages.get(0);
		initYears();
		year = years.get(0);
	}
	
	public void initBreakerResponseTimeStatistics() {
		Calendar cal = Calendar.getInstance();
		Integer currentYear = cal.get(Calendar.YEAR);
		Integer currentMonth = cal.get(Calendar.MONTH )+1;
		year = currentYear.toString();
		month = currentMonth.toString();
		if(!years.contains(year)) {
			year = years.get(0);
		}
		voltage = "all";
		area = "all";
		breakerResponseTimeStatisticsList = manager.queryByCondition(year, month, area, voltage);
	}
	
	public void preCreatBreakerResponseTimeStatistics() {
		breakerResponseTimeStatistics = new BreakerResponseTimeStatistics();
	}
	
	public void editBreakerResponseTimeStatistics() {
		breakerResponseTimeStatistics = selectBreakerResponseTimeStatistics;
	}
	
	public void saveBreakerResponseTimeStatistics() {
		if(breakerResponseTimeStatistics != null) {
			if(breakerResponseTimeStatistics.getId() == null) {//新建
				if(isNotExit(breakerResponseTimeStatistics)) {
					breakerResponseTimeStatistics.setVoltageLevel(breakerResponseTimeStatistics.getVoltageLevel()+"KV");
					BreakerResponseTimeStatistics brts = manager.createOrUpdate(breakerResponseTimeStatistics);
					breakerResponseTimeStatisticsList.add(brts);
				} else {
					addErrorMessage("记录已存在，添加失败！");
					return;
				}
			} else {//编辑
				breakerResponseTimeStatisticsList.set(breakerResponseTimeStatisticsList.indexOf(breakerResponseTimeStatistics), breakerResponseTimeStatistics);
				manager.createOrUpdate(breakerResponseTimeStatistics);
				selectBreakerResponseTimeStatistics = new BreakerResponseTimeStatistics();
			}
			addSuccessMessage("保存成功！");
			years.clear();
			initYears();
		}
	}
	
	private boolean isNotExit(BreakerResponseTimeStatistics b) {
		boolean flag = false;
		List<BreakerResponseTimeStatistics> brts = manager.queryByCondition(b.getYear().toString(), b.getMonth().toString(), b.getArea(),b.getVoltageLevel());
		if(brts.size() == 0) {
			//当前记录不存在
			flag = true;
		}
		return flag;
	}
	
	public void deleteBreakerResponseTimeStatistics() {
		if(selectBreakerResponseTimeStatistics != null && !selectBreakerResponseTimeStatistics.getId().isEmpty()) {
			manager.deleteById(selectBreakerResponseTimeStatistics.getId());
			breakerResponseTimeStatisticsList.remove(selectBreakerResponseTimeStatistics);
			addSuccessMessage("删除成功！");
			years.clear();
			initYears();
			selectBreakerResponseTimeStatistics = new BreakerResponseTimeStatistics();
		} else {
			addErrorMessage("请选择要删除的数据！");
		}
	}
	
	/**
	 * 模板下载
	 */
	public void fileDownloadView() {
		InputStream stream = null;
		try {
			stream = new FileInputStream(new File(pros.getTempletePath()+"countBreakerResponseTime.xlsx"));
			templateFile = new DefaultStreamedContent(stream, "xlsx", "countBreakerResponseTime.xlsx");
		} catch (FileNotFoundException e) {
			addErrorMessage("下载文件失败，请联系技术人员！");
			e.printStackTrace();
		}
	}

	public void chooseEquipment() {
        Map<String,Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", true);
        options.put("width", 600);
        options.put("height", 200);
        
        Map<String,List<String>> params = new HashMap<>();
        List<String> param = new ArrayList<>();
        param.add("1");	//设置去除前几行
        params.put("ingnoreRows", param);
        openDialog("/ui/common/upload_excel_define", params, options);
    }
	
	public void onSelectorChosen(SelectEvent event) {
		List<List<String>>objs = (List<List<String>>) event.getObject();
		List<BreakerResponseTimeStatistics> temp = new ArrayList<>();
		List<Integer> errorList = new ArrayList<Integer>();
		int i = 0;
		try {
			for (List<String> list : objs) {
				i++;
				//单位	年	月	断路器平均动作时间	断路器最长动作时间	电压等级
				BreakerResponseTimeStatistics brts  = new BreakerResponseTimeStatistics();
				int year = NumberFormat.getInstance().parse(list.get(1).toString()).intValue();
				int month = NumberFormat.getInstance().parse(list.get(2).toString()).intValue();
				if(year > 1970 && year < 2200) {
					if(month > 0 && month < 13) {
						brts.setArea(list.get(0));
						brts.setYear(year);
						brts.setMonth(month);
						brts.setAvgActTime(list.get(3));
						brts.setMaxActTime(list.get(4));
						brts.setVoltageLevel(list.get(5));
						temp.add(brts);
					} else {
						errorList.add(i);
						continue;
					}
				} else {
					errorList.add(i);
					continue;
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			addErrorMessage("表格数字有误，请仔细核对！");
			return ;
		}
		if(temp.size() !=0) {
			for(BreakerResponseTimeStatistics brt:temp) {
				if(isNotExit(brt)) {
					manager.createOrUpdate(brt);
				}
			}
			years.clear();
			initYears();
			addSuccessMessage("文件上传成功");
		}
		if(errorList.size() != 0) {
			String errorRecord = "";
			for(int j = 0; j<errorList.size(); j++) {
				errorRecord += errorList.get(j) + " ";
			}
			addErrorMessage("文件第"+errorRecord+"行有误，上传失败");
		}
		breakerResponseTimeStatisticsList = manager.getAllBreakerResponseTimeStatistics();
	}
	
	public void search() {
		String y = "";
		if(!(years.get(0).equals(year)) && !"".equals(year)) {
			y = year.substring(0, 4);
		}
		breakerResponseTimeStatisticsList = manager.queryByCondition(y, month, area, voltage);
	}
	
	public void reset(){
		month = "all";
		area = "all";
		year = years.get(0);
		search();
	}
	
	public void onRowSelect(SelectEvent event) {
		selectBreakerResponseTimeStatistics = (BreakerResponseTimeStatistics) event.getObject();
	}
	
	public List<String> completeArea(String query) {
		return areas;
	}
	
	public List<String> getYears() {
		return years;
	}

	public void setYears(List<String> years) {
		this.years = years;
	}

	public List<BreakerResponseTimeStatistics> getBreakerResponseTimeStatisticsList() {
		return breakerResponseTimeStatisticsList;
	}

	public void setBreakerResponseTimeStatisticsList(
			List<BreakerResponseTimeStatistics> breakerResponseTimeStatisticsList) {
		this.breakerResponseTimeStatisticsList = breakerResponseTimeStatisticsList;
	}

	public BreakerResponseTimeStatistics getBreakerResponseTimeStatistics() {
		return breakerResponseTimeStatistics;
	}

	public void setBreakerResponseTimeStatistics(
			BreakerResponseTimeStatistics breakerResponseTimeStatistics) {
		this.breakerResponseTimeStatistics = breakerResponseTimeStatistics;
	}

	public BreakerResponseTimeStatistics getSelectBreakerResponseTimeStatistics() {
		return selectBreakerResponseTimeStatistics;
	}

	public void setSelectBreakerResponseTimeStatistics(
			BreakerResponseTimeStatistics selectBreakerResponseTimeStatistics) {
		this.selectBreakerResponseTimeStatistics = selectBreakerResponseTimeStatistics;
	}

	public List<Integer> getMonths() {
		return months;
	}

	public void setMonths(List<Integer> months) {
		this.months = months;
	}

	public StreamedContent getTemplateFile() {
		return templateFile;
	}

	public void setTemplateFile(StreamedContent templateFile) {
		this.templateFile = templateFile;
	}

	public String getArea() {
		return area;
	}

	public void setArea(String area) {
		this.area = area;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public List<String> getAreas() {
		return areas;
	}

	public void setAreas(List<String> areas) {
		this.areas = areas;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}

	public List<String> getVoltages() {
		return voltages;
	}

	public void setVoltages(List<String> voltages) {
		this.voltages = voltages;
	}

	public String getVoltage() {
		return voltage;
	}

	public void setVoltage(String voltage) {
		this.voltage = voltage;
	}
	
}
